package com.qf.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.qf.pojo.TbUser;
import com.qf.vo.BaseResult;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * Created by 54110 on 2021/4/16.
 */
public class MyInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

       //判断用户是否登录
        HttpSession session = request.getSession();
        TbUser user = (TbUser) session.getAttribute("user");
        if (user!=null){
            return true;
        }
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        //声明返回
        BaseResult baseResult = new BaseResult();
        baseResult.setMessage("未登录！请先登录！");
        baseResult.setCode(20001);
        //将返回转为json格式
        String string = JSONObject.toJSONString(baseResult);
        writer.write(string);
        return false;
    }
}
